package longcaisuyun.longcai.com.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import longcaisuyun.longcai.com.yiliubabalongcaisuyun.AbstractWheelTextAdapter;
import longcaisuyun.longcai.com.yiliubabalongcaisuyun.MyApplication;
import longcaisuyun.longcai.com.yiliubabalongcaisuyun.R;


//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//         佛祖保佑             永无BUG
//         佛曰:
//                  写字楼里写字间，写字间里程序员；
//                  程序人员写程序，又拿程序换酒钱。
//                  酒醒只在网上坐，酒醉还来网下眠；
//                  酒醉酒醒日复日，网上网下年复年。
//                  但愿老死电脑间，不愿鞠躬老板前；
//                  奔驰宝马贵者趣，公交自行程序员。
//                  别人笑我忒疯癫，我笑自己命太贱；
//                  不见满街漂亮妹，哪个归得程序员？
/************************************************************/
//
/************************************************************/

/**
 * 更改封面对话�?
 * 
 * @author ywl
 *
 */
public class ChangeAddressDialog extends Dialog implements
		View.OnClickListener {

	private WheelView wvProvince;
	private WheelView wvCitys;
	private View lyChangeAddress;
	private View lyChangeAddressChild;
	private TextView btnSure;
	private TextView btnCancel;

	private Context context;
	private JSONObject mJsonObj;
	private String[] mProvinceDatas;
	private Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();

	private ArrayList<String> arrProvinces = new ArrayList<String>();
	private ArrayList<String> arrCitys = new ArrayList<String>();
	private AddressTextAdapter provinceAdapter;
	private AddressTextAdapter cityAdapter;

	private String strProvince = "面包车1";
	private String strCity = "1";
	private OnAddressCListener onAddressCListener;

	private int maxsize = 24;
	private int minsize = 18;

	public ChangeAddressDialog(Context context,ArrayList<String>list,Map<String, String[]> m) {
		super(context, R.style.ShareDialog);
		this.context = context;
		this.arrProvinces=list;
		this.mCitisDatasMap=m;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_che_leibie);
		View  view=getWindow().getDecorView();
		MyApplication.ScaleScreenHelper.loadView((ViewGroup)view);

		wvProvince = (WheelView) findViewById(R.id.wv_address_province);
		wvCitys = (WheelView) findViewById(R.id.wv_address_city);

		btnSure = (TextView) findViewById(R.id.btn_myinfo_sure);
		btnCancel = (TextView) findViewById(R.id.btn_myinfo_cancel);


		btnSure.setOnClickListener(this);
		btnCancel.setOnClickListener(this);

		// initJsonData();
		// initDatas();
//		initdata();
		initProvinces();
		provinceAdapter = new AddressTextAdapter(context, arrProvinces,
				getProvinceItem(strProvince), maxsize, minsize);
		wvProvince.setVisibleItems(5);
		wvProvince.setViewAdapter(provinceAdapter);
		wvProvince.setCurrentItem(getProvinceItem(strProvince));

		initCitys(mCitisDatasMap.get(strProvince));
		cityAdapter = new AddressTextAdapter(context, arrCitys,
				getCityItem(strCity), maxsize, minsize);
		wvCitys.setVisibleItems(5);
		wvCitys.setViewAdapter(cityAdapter);
		wvCitys.setCurrentItem(getCityItem(strCity));

		wvProvince.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				String currentText = (String) provinceAdapter.getItemText(wheel
						.getCurrentItem());
				strProvince = currentText;
				setTextviewSize(currentText, provinceAdapter);
				String[] citys = mCitisDatasMap.get(currentText);
				initCitys(citys);
				cityAdapter = new AddressTextAdapter(context, arrCitys, 0,
						maxsize, minsize);
				wvCitys.setVisibleItems(5);
				wvCitys.setViewAdapter(cityAdapter);
				wvCitys.setCurrentItem(0);
			}
		});

		wvProvince.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				// TODO Auto-generated method stub
				String currentText = (String) provinceAdapter.getItemText(wheel
						.getCurrentItem());
				setTextviewSize(currentText, provinceAdapter);
			}
		});

		wvCitys.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				String currentText = (String) cityAdapter.getItemText(wheel
						.getCurrentItem());
				strCity = currentText;
				setTextviewSize(currentText, cityAdapter);
			}
		});

		wvCitys.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				// TODO Auto-generated method stub
				String currentText = (String) cityAdapter.getItemText(wheel
						.getCurrentItem());
				setTextviewSize(currentText, cityAdapter);
			}
		});
	}

	private void initdata() {
		// private ArrayList<String> arrProvinces = new ArrayList<String>();
		// private ArrayList<String> arrCitys = new ArrayList<String>();
		arrProvinces.add("面包车");
		arrProvinces.add("面包车1");
		arrProvinces.add("面包车2");
		arrProvinces.add("面包车3");
		arrProvinces.add("面包车4");
		arrProvinces.add("面包车5");
		arrProvinces.add("面包车6");
		arrProvinces.add("面包车7");
		arrProvinces.add("面包车8");
		arrProvinces.add("面包车9");
		arrProvinces.add("面包车10");
		arrProvinces.add("面包车11");
		arrCitys.add("1");
		arrCitys.add("2");
		arrCitys.add("3");
		arrCitys.add("4");
		arrCitys.add("5");
		arrCitys.add("6");

		arrCitys.add("7");
		arrCitys.add("8");

		arrCitys.add("9");
		arrCitys.add("10");
		arrCitys.add("11");

		arrCitys.add("12");

	}

	private class AddressTextAdapter extends AbstractWheelTextAdapter {
		ArrayList<String> list;

		protected AddressTextAdapter(Context context, ArrayList<String> list,
				int currentItem, int maxsize, int minsize) {
			super(context, R.layout.item_ziliao, NO_RESOURCE, currentItem,
					maxsize, minsize);
			this.list = list;
			setItemTextResource(R.id.t_ziliao);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			View view = super.getItem(index, cachedView, parent);
			return view;
		}

		@Override
		public int getItemsCount() {
			return list.size();
		}

		@Override
		protected CharSequence getItemText(int index) {
			return list.get(index) + "";
		}
	}

	/**
	 * 设置字体大小
	 * 
	 * @param curriteItemText
	 * @param adapter
	 */
	public void setTextviewSize(String curriteItemText,
			AddressTextAdapter adapter) {
		ArrayList<View> arrayList = adapter.getTestViews();
		int size = arrayList.size();
		String currentText;
		for (int i = 0; i < size; i++) {
			TextView textvew = (TextView) arrayList.get(i);
			currentText = textvew.getText().toString();
			if (curriteItemText.equals(currentText)) {
				textvew.setTextSize(maxsize);
			} else {
				textvew.setTextSize(minsize);
			}
		}
	}

	public void setAddresskListener(OnAddressCListener onAddressCListener) {
		this.onAddressCListener = onAddressCListener;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == btnSure) {
			if (onAddressCListener != null) {
				onAddressCListener.onClick(strProvince, strCity);
			}
		} else if (v == btnCancel) {

		} else if (v == lyChangeAddressChild) {
			return;
		} else {
			dismiss();
		}
		dismiss();
	}

	/**
	 * 回调接口
	 * 
	 * @author Administrator
	 *
	 */
	public interface OnAddressCListener {
		public void onClick(String province, String city);
	}

	// /**
	// * 从文件中读取地址数据
	// */
	// private void initJsonData() {
	// try {
	// StringBuffer sb = new StringBuffer();
	// InputStream is = context.getAssets().open("city.json");
	// int len = -1;
	// byte[] buf = new byte[1024];
	// while ((len = is.read(buf)) != -1) {
	// sb.append(new String(buf, 0, len, "gbk"));
	// }
	// is.close();
	// mJsonObj = new JSONObject(sb.toString());
	// } catch (IOException e) {
	// e.printStackTrace();
	// } catch (JSONException e) {
	// e.printStackTrace();
	// }
	// }
	//
	// /**
	// * 解析数据
	// */
	// private void initDatas() {
	// try {
	// JSONArray jsonArray = mJsonObj.getJSONArray("citylist");
	// mProvinceDatas = new String[jsonArray.length()];
	// for (int i = 0; i < jsonArray.length(); i++) {
	// JSONObject jsonP = jsonArray.getJSONObject(i);
	// String province = jsonP.getString("p");
	//
	// mProvinceDatas[i] = province;
	//
	// JSONArray jsonCs = null;
	// try {
	// /**
	// * Throws JSONException if the mapping doesn't exist or is
	// * not a JSONArray.
	// */
	// jsonCs = jsonP.getJSONArray("c");
	// } catch (Exception e1) {
	// continue;
	// }
	// String[] mCitiesDatas = new String[jsonCs.length()];
	// for (int j = 0; j < jsonCs.length(); j++) {
	// JSONObject jsonCity = jsonCs.getJSONObject(j);
	// String city = jsonCity.getString("n");
	// mCitiesDatas[j] = city;
	// JSONArray jsonAreas = null;
	// try {
	// /**
	// * Throws JSONException if the mapping doesn't exist or
	// * is not a JSONArray.
	// */
	// jsonAreas = jsonCity.getJSONArray("a");
	// } catch (Exception e) {
	// continue;
	// }
	//
	// String[] mAreasDatas = new String[jsonAreas.length()];
	// for (int k = 0; k < jsonAreas.length(); k++) {
	// String area = jsonAreas.getJSONObject(k).getString("s");
	// mAreasDatas[k] = area;
	// }
	// }
	// mCitisDatasMap.put(province, mCitiesDatas);
	// }
	//
	// } catch (JSONException e) {
	// e.printStackTrace();
	// }
	// mJsonObj = null;
	// }

	/**
	 * 初始化省�?
	 */
	public void initProvinces() {
//		int length = arrProvinces.size();
//		for (int i = 0; i < length; i++) {
//			arrProvinces.add(arrProvinces.get(i));
//		}
	}

	/**
	 * 根据省会，生成该省会的所有城�?
	 * 
	 * @param citys
	 */
	public void initCitys(String[] citys) {
		if (citys != null) {
			arrCitys.clear();
			int length = citys.length;
			for (int i = 0; i < length; i++) {
				arrCitys.add(citys[i]);
			}
		} else {
			String[] city = mCitisDatasMap.get("面包车1");
			arrCitys.clear();
			int length = city.length;
			for (int i = 0; i < length; i++) {
				arrCitys.add(citys[i]);
			}
		}
		if (arrCitys != null && arrCitys.size() > 0
				&& !arrCitys.contains(strCity)) {
			strCity = arrCitys.get(0);
		}
	}

	/**
	 * 初始化地�?
	 * 
	 * @param province
	 * @param city
	 */
	public void setAddress(String province, String city) {
		if (province != null && province.length() > 0) {
			this.strProvince = province;
		}
		if (city != null && city.length() > 0) {
			this.strCity = city;
		}
	}

	/**
	 * 返回省会索引，没有就返回默认“四川�??
	 * 
	 * @param province
	 * @return
	 */
	public int getProvinceItem(String province) {
		int size = arrProvinces.size();
		int provinceIndex = 0;
		boolean noprovince = true;
		for (int i = 0; i < size; i++) {
			if (province.equals(arrProvinces.get(i))) {
				noprovince = false;
				return provinceIndex;
			} else {
				provinceIndex++;
			}
		}
		if (noprovince) {
			strProvince = arrProvinces.get(0);
			return 0;
		}
		return provinceIndex;
	}

	/**
	 * 得到城市索引，没有返回默认�?�成都�??
	 * 
	 * @param city
	 * @return
	 */
	public int getCityItem(String city) {
		int size = arrCitys.size();
		int cityIndex = 0;
		boolean nocity = true;
		for (int i = 0; i < size; i++) {
			System.out.println(arrCitys.get(i));
			if (city.equals(arrCitys.get(i))) {
				nocity = false;
				return cityIndex;
			} else {
				cityIndex++;
			}
		}
		if (nocity) {
			strCity = arrCitys.get(0);
			return 0;
		}
		return cityIndex;
	}

}